package com.css.zfzx.sjcj.modules.qhriskvisualshow.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.sjcj.common.utils.VectorDataUtil;
import com.css.zfzx.sjcj.common.utils.ZipDownloadUtil;
import com.css.zfzx.sjcj.modules.qhmapfiles.service.QhMapFilesService;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.entity.QhProbabilityEarthquakeDangerEntity;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.service.QhProbabilityEarthquakeDangerService;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.viewobjects.QhProbabilityEarthquakeDangerQueryParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author andy
 * @date 2021-01-26
 */
@Slf4j
@RestController
@RequestMapping("/qh/qhProbabilityEarthquakeDangers")
public class QhProbabilityEarthquakeDangerController {
    @Autowired
    private QhProbabilityEarthquakeDangerService qhProbabilityEarthquakeDangerService;
    @Autowired
    private QhMapFilesService qhMapFilesService;

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    @GetMapping("/queryQhProbabilityEarthquakeDangers")
    public RestResponse queryQhSiteClassResults(HttpServletRequest request, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = qhProbabilityEarthquakeDangerService.queryQhProbabilityEarthquakeDangers(queryParams, curPage, pageSize);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryQhProbabilityEarthquakeDangersByFileName")
    public RestResponse queryQhProbabilityEarthquakeDangersByFileName(HttpServletRequest request, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        RestResponse response = null;
        try {
            String sort = request.getParameter("sort"), order = request.getParameter("order");
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = qhProbabilityEarthquakeDangerService.queryQhProbabilityEarthquakeDangersByFileName(queryParams, curPage, pageSize, sort, order);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("{id}")
    public RestResponse getProbabilityEarthquakeDanger(@PathVariable String id) {
        RestResponse response = null;
        try {
            QhProbabilityEarthquakeDangerEntity qhSiteClassResult = qhProbabilityEarthquakeDangerService.getQhProbabilityEarthquakeDangerById(id);
            response = RestResponse.succeed(qhSiteClassResult);
        } catch (Exception e) {
            String errorMessage = "获取失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @GetMapping("/queryQhProbabilityEarthquakeDangersById")
    public RestResponse getProbabilityEarthquakeDangerById(HttpServletRequest request, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = qhProbabilityEarthquakeDangerService.queryQhProbabilityEarthquakeDangers(queryParams, curPage, pageSize);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "获取失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }


    @PostMapping
    public RestResponse saveProbabilityEarthquakeDanger(@RequestBody QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            qhProbabilityEarthquakeDangerService.saveQhProbabilityEarthquakeDanger(qhProbabilityEarthquakeDanger);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "新增失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }

    @PutMapping
    public RestResponse updateProbabilityEarthquakeDanger(@RequestBody QhProbabilityEarthquakeDangerEntity qhProbabilityEarthquakeDanger) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            qhProbabilityEarthquakeDangerService.updateQhProbabilityEarthquakeDanger(qhProbabilityEarthquakeDanger);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @DeleteMapping
    public RestResponse deleteProbabilityEarthquakeDangers(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            qhProbabilityEarthquakeDangerService.deleteQhProbabilityEarthquakeDangers(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @DeleteMapping("/deleteQhProbabilityEarthquakeDangersByFileNames")
    public RestResponse deleteProbabilityEarthquakeDangersByFileNames(@RequestParam String fileNames, @RequestParam String province) {
        RestResponse response = null;
        JSONObject json = new JSONObject();

        String[] _fileNames = null;
        List<String> params = new ArrayList<>();
        if (fileNames.indexOf(",") >= 0) {
            _fileNames = StringUtils.split(fileNames, ",");
            params = Arrays.asList(_fileNames);
        } else {
            params = Arrays.asList(fileNames);
        }

        int idx = -1;
        try {
            idx = qhProbabilityEarthquakeDangerService.deleteQhProbabilityEarthquakeDangersByFileName(params, province);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除第" + idx + "条数据出现异常!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping("/getQhProbabilityEarthquakeDangers")
    public RestResponse getQhProbabilityEarthquakeDangers(HttpServletRequest request, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        RestResponse response = null;
        try {
            JSONObject jsonObject = qhProbabilityEarthquakeDangerService.getQhProbabilityEarthquakeDangers(queryParams);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping("/searchQhProbabilityEarthquakeDangers")
    public RestResponse searchQhProbabilityEarthquakeDangers(HttpServletRequest request, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        RestResponse response = null;
        try {
            JSONObject jsonObject = qhProbabilityEarthquakeDangerService.searchQhProbabilityEarthquakeDangers(queryParams);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/upload")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");

        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        if ("".equals(province) ) return RestResponse.fail("请选择场地所在省份!");
        if ("".equals(city)) return RestResponse.fail("请选择场地所在城市!");
        //if ("".equals(area)) return RestResponse.fail("请选择场地所在区县!");

        //判断是否已上传未保存文件--上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        int fileCount = qhMapFilesService.lookUpMapFiles("0","PED_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件等待数据入库, 若要上传最新数据请第二天在【图层管理】功能中删除数据.");

        //判断是否已上传正在保存文件--上传类型（PED_,RLM_,RLMPolygon_,SCR_）
        fileCount = qhMapFilesService.lookUpMapFiles("2","PED_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件数据正在入库, 若要上传最新数据请第二天在【图层管理】功能中删除数据.");

        //判断是否已存在上传数据
        int count = qhProbabilityEarthquakeDangerService.lookUpQhProbabilityEarthquakeDangers(queryParams, true);
        if (count > 0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【图层管理】功能中删除数据.");


        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String gdbFileName = "";//gdb文件名
        String jxfilename = "";//shp文件名
        String dbffilename = "";
        String formatDate = VectorDataUtil.getFormatDate();
        //判断是否为GDB文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            if (oldFileName.equals("gdb")) {//是否存在gdb文件
                String fName = "新建文件地理数据库";
                String postfix = ".gdb";
                String prefix = "PED_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                gdbFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                break;
            }
        }
        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
                newFileName = gdbFileName + "/"+oldFileName;
            }else{//SHP文件
                // 上传后文件名
                String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
                String prefix = "PED_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                    jxfilename = newFileName;
                }
                if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                    dbffilename = newFileName;
                }
            }

            File savefile = new File(uploadPath + newFileName);
            String absolutePath = savefile.getAbsolutePath();
            File absoluteFile = savefile.getAbsoluteFile();
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            //if (savefile.exists() && savefile.delete()) {
                //return RestResponse.fail("Destination file [" + savefile.getAbsolutePath() + "] already exists and could not be deleted,请手动删除文件");
            //}
            try {
                //file.transferTo(savefile);
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename+gdbFileName);
        /*
        String[] paramdatas = VectorDataUtil.getFieldName(uploadPath + dbffilename, "GBK");
        if (paramdatas != null && paramdatas.length > 0) {
            String str = qhProbabilityEarthquakeDangerService.judgeFileParams(paramdatas);
            if (str != "" && str != null && str.length() > 0) {
                //todo:删除对应的文件
                return RestResponse.fail("导入数据参数不正确，参数必须包含【" + str + "】");
            }
        } else {
            //todo:删除对应的文件
            return RestResponse.fail("导入的dbf文件参数不能为空。");
        }*/
        /*if (!(VectorDataUtil.checkCGCS2000(uploadPath + jxfilename))) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        System.out.println(new Date()+"-----------3.开始importShapeFile");
        String resMsg = qhProbabilityEarthquakeDangerService.checkSHPFiles(uploadPath + jxfilename, province, city, area);
        System.out.println(new Date()+"-----------4.结束importShapeFile");*/
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
            resultMsg = gdbFileName;//返回GDB文件名
            System.out.println(new Date()+"-----------3.开始importGDBFile");
            resMsg = qhProbabilityEarthquakeDangerService.checkGDBFiles(uploadPath + gdbFileName, province, city, area);
            System.out.println(new Date()+"-----------4.结束importGDBFile");
            if (resMsg.indexOf("spatialReferenceError") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据.");
        }else{//SHP文件
            if (!(VectorDataUtil.checkCGCS2000(uploadPath + jxfilename))) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
            System.out.println(new Date()+"-----------3.开始importShapeFile");
            resMsg = qhProbabilityEarthquakeDangerService.checkSHPFiles(uploadPath + jxfilename, province, city, area);
            System.out.println(new Date()+"-----------4.结束importShapeFile");
        }
        if(resMsg.indexOf("等待导入") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed("上传文件中字段值存在空值, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("PointIsNotInDistrict") != -1) return RestResponse.succeed("存在没有位于 【" + province + city + area + "】 行政边界的数据, 请检查数据的正确性.");
        /*if (resMsg.indexOf("BasementGreaterPlace") != -1) return RestResponse.succeed("场地数值应大于等于基岩数值, 请检查关联数据的正确性.");*/
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed("填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if (resMsg.indexOf("SpatialResolutionError") != -1) return RestResponse.succeed("上传数据空间分辨率不是6秒, 请检查数据的正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        if(resMsg.indexOf("PointOverlapError")!=-1) return RestResponse.succeed("上传文件中数据存在空间位置重叠, 请检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }
    @PostMapping("/postUpload")
    public RestResponse uploadSpaceData(QhProbabilityEarthquakeDangerQueryParams queryParams) {
        String jxfilename = queryParams.getAffiliatedFileName(), province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        String resultMsg = "";
        String resMsg = qhProbabilityEarthquakeDangerService.checkSHPFiles(uploadPath + jxfilename, province, city, area);
        if(resMsg.indexOf("等待导入") != -1){//上传成功
            System.out.println(new Date()+"-----------上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------上传失败." + resMsg);
        }
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed("上传文件中字段值存在空值, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("PointIsNotInDistrict") != -1) return RestResponse.succeed("存在没有位于 【" + province + city + area + "】 行政边界的数据, 请检查数据的正确性.");
        /*if (resMsg.indexOf("BasementGreaterPlace") != -1) return RestResponse.succeed("场地数值应大于等于基岩数值, 请检查关联数据的正确性.");*/
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed("填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if (resMsg.indexOf("SpatialResolutionError") != -1) return RestResponse.succeed("上传数据空间分辨率不是6秒, 请检查数据的正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        if(resMsg.indexOf("PointOverlapError")!=-1) return RestResponse.succeed("上传文件中数据存在空间位置重叠, 请检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

        /**
         * 批量下载文件
         *
         * @param response
         * @return
         */
    @GetMapping("/download")
    public RestResponse downloadFile(HttpServletResponse response, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        //获取指定路径下的所有文件名
        File file = new File(uploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea(), affiliatedFileName = queryParams.getAffiliatedFileName();
        //String tempFileName = (province == "" ? "0" : province) + "_" + (city == "" ? "0" : city) + "_" + (area == "" ? "0" : area) + "_" + (affiliatedFileName == "" ? "0" : affiliatedFileName);
        String tempFileName = affiliatedFileName;
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            //if (_temp.indexOf(tempFileName) != -1 && _temp.indexOf(province) != -1 && _temp.indexOf(city) != -1 && _temp.indexOf(area) != -1) _files.add(files[i]);
            if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, zipFiles);
            sb.append(msg);
            return null;
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, new ArrayList<File>());
            return null;
        }
    }

    @GetMapping("/download0")
    public RestResponse downloadFile0(HttpServletResponse response, QhProbabilityEarthquakeDangerQueryParams queryParams) {
        //获取指定路径下的所有文件名
        File file = new File(uploadPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        String tempFileName = "PED_" + (province == "" ? "0" : province) + "_" + (city == "" ? "0" : city) + "_" + (area == "" ? "0" : area);
        String _temp = "";
        List<File> _files = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            _temp = files[i].getName();
            if (_temp.indexOf(tempFileName) != -1) _files.add(files[i]);
        }
        List<File> zipFiles = _files;
        //List<File> zipFiles = new ArrayList<>(Arrays.asList(files));
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, zipFiles);
            sb.append(msg);
            return null;
        } else {
            /*sb.append("没有可下载文件");
            return RestResponse.succeed(sb);*/
            String zipName = tempFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, uploadPath, zipName, new ArrayList<File>());
            return null;
        }
    }
}